package com.ebupt.migu.music.redis.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Administrator
 * @date 2017/12/1
 */
@Service
@Slf4j
public class RedisService {

    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean setSet(final String key, Set value) {
        boolean result = false;
        try {
            SetOperations<Serializable, Object> operations = redisTemplate.opsForSet();
            for (Object obj: value) {
                operations.add(key, obj);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean setManyValueSet(final String key, Set value) throws Exception {
        boolean result = false;
        try {
            SetOperations<Serializable, Object> operations = redisTemplate.opsForSet();
            int size = value.size();
            if(size>=1000000){
                if(size>3000000){
                    if(size>7000000){
                        throw new IllegalStateException("文件过大");
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Set insertValue = new HashSet();
                            Iterator iterator = value.iterator();
                            while (iterator.hasNext()){
                                Object next = iterator.next();
                                insertValue.add(next);
                                if(insertValue.size()>=100000){
                                    operations.add(key,insertValue.toArray());
                                    insertValue = new HashSet();
                                    redisTemplate.expire(key,90,TimeUnit.DAYS);

                                }
                            }
                            redisTemplate.expire(key,90,TimeUnit.DAYS);
                            if(insertValue.size()>0){
                                operations.add(key,insertValue.toArray());
                            }
                        }
                    }).start();
                }else {
                    Set insertValue = new HashSet();
                    Iterator iterator = value.iterator();
                    while (iterator.hasNext()){
                        Object next = iterator.next();
                        insertValue.add(next);
                        if(insertValue.size()>=100000){
                            operations.add(key,insertValue.toArray());
                            insertValue = new HashSet();
                        }
                    }
                    if(insertValue.size()>0){
                        operations.add(key,insertValue.toArray());
                    }
                }
            }else {
                operations.add(key,value.toArray());
            }
            redisTemplate.expire(key,90,TimeUnit.DAYS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }
    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove_key(key);
        }
    }

    /**
     * 批量删除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
    /**
     * 删除对应的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
            redisTemplate.opsForSet().remove(key);
        }
    }





    public void deleteKeyByKey(final String key) {
        if (exists(key)) {
            redisTemplate.unlink(key);
        }
    }
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Set<Object> getSet(final String key) {
        Set<Object> resultSet =redisTemplate.opsForSet().members(key);
        return resultSet;
    }
    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     * 列表获取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    /**
     * 交集
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void intersectAndStore(String sourceSet1, String sourceSet2, String targetSet){
        redisTemplate.opsForSet().intersectAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 交集
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set intersect(String sourceSet1, String sourceSet2){
        return redisTemplate.opsForSet().intersect(sourceSet1, sourceSet2);
    }

    /**
     * 并集
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void unionAndStore(String sourceSet1, String sourceSet2, String targetSet){
        redisTemplate.opsForSet().unionAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 并集
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set union(String sourceSet1, String sourceSet2){
        return redisTemplate.opsForSet().union(sourceSet1, sourceSet2);
    }

    /**
     * 差集
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void differenceAndStore(String sourceSet1, String sourceSet2, String targetSet){
        redisTemplate.opsForSet().differenceAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 差集
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set difference(String sourceSet1, String sourceSet2, String targetSet){
        return redisTemplate.opsForSet().difference(sourceSet1, sourceSet2);
    }

    /**
     * 类型
     * @param type
     * @return
     */
    public DataType type(String type){
        return redisTemplate.type("type");
    }
    /**
     * 长度
     * @param key
     * @return
     */
    public long length(String key){
        if(redisTemplate.hasKey(key)){
           return redisTemplate.opsForSet().size(key);
        }
        return 0;
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove_key(final String key) {
        if (exists(key)) {
            redisTemplate.unlink(key);
        }
    }

    /**
     * 从redis中获取key对应的过期时间
     *
     * @param key key
     * @return 过期时间
     */
    public Long getExpire(final String key) {
        return redisTemplate.opsForValue().getOperations().getExpire(key, TimeUnit.MILLISECONDS);
    }

    /**
     * 更新key的过期时间
     *
     * @param key key
     * @param expireTime 过期时间
     */
    public void updateKeyExpireTime(final String key, Long expireTime) {
        redisTemplate.opsForValue().getOperations().expire(key, expireTime, TimeUnit.MILLISECONDS);
    }

    /**
     * 将set集合存入redis中
     *
     * @param key        redis的key
     * @param value      set集合
     * @param expireTime 过期时间
     */
    public void setCollectToRedis(final String key, Set<String> value, Long expireTime) {
        try {
            SetOperations opsForSet = redisTemplate.opsForSet();
            int size = value.size();
            if (size >= 1000000) {
                ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                        10,
                        5000,
                        TimeUnit.MILLISECONDS,
                        new ArrayBlockingQueue<>(5),
                        new NamedThreadFactory("setRedis-thread-pool"),
                        new ThreadPoolExecutor.AbortPolicy());
                executor.submit(() -> {
                    Set<String> set = new HashSet<>();
                    for (String next : value) {
                        set.add(next);
                        if (set.size() >= 100000) {
                            opsForSet.add(key, set.toArray());
                            set = new HashSet<>();
                            redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
                        }
                    }
                    if (set.size() > 0) {
                        opsForSet.add(key, set.toArray());
                        redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
                    }
                });
                executor.shutdown();
            } else {
                opsForSet.add(key, value.toArray());
                redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
            }
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 扫描redis中是否含有key
     *
     * @param key key
     * @return 扫描光标集合
     */
    public Cursor<String> scan(String key) {
        return redisTemplate.opsForSet().scan(key, ScanOptions.NONE);
    }




    /**
     * 扫描redis中是否含有key
     *
     * @param key key
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 扫描redis中的key值
     *
     * @param key key
     */
    public void deleteKeys(String key) {
        Set<String> keys = redisTemplate.keys(key);
        if (CollectionUtil.isNotEmpty(keys)) {
            log.info("共有{}个key", keys.size());
            redisTemplate.delete(keys);
        }
    }
}